const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))

var mac = ""

async function snCheck(){
    result = await window.pywebview.api.snCheck()
    if ( result == false){
        $("#labelDate").html("[未激活]")
        showModel("没有购买或已经到期, 请用微信扫二维码进行购买")
    } else {
        $("#labelDate").html("["+ result +"]")
        showModel("感谢支持, 到期时间为: " + result)
    }
}

$(document).ready(function() {
    $("#btnContractsGo").click(async function() {
        if (saveConfig() != false){
            if ($('#radioImage').is(":checked")) {
                copyImageToClipboard('tempImages.jpg')  // 可以改为python端去拷
            }
    
            showModel(await window.pywebview.api.contractsGo())
        }

    });

    $("#btnGroupGo").click(async function() {
        if (saveConfig() != false){
            showModel(await window.pywebview.api.groupGo())
        }
    });

    $("#btnFriendGo").click(async function() {
        if (saveConfig() != false){
            showModel(await window.pywebview.api.friendGo())
        }
    });

    $("#btnMomentGo").click(async function() {
        if (saveConfig() != false){
            result = await window.pywebview.api.momentGo()
            if (result == true || $.trim(result) == "") 
                showModel("任务执行完毕")
            else
                showModel(result)
        }
    });

    $("#btnSave").click(async function() {
        if (saveConfig() != false){
            saveConfig()
        }
    });
    
    $("#btnReadImage").click(async function() {
        src = $("#inputImage").val()

        if (src.length <= 5){
            showModel("图片地址或路径不正确, 请重新输入!")
            return
        }

        result = await window.pywebview.api.copyImage(src)
        
        if (result == true)
            $("#image").attr("src", "tempImages.jpg?time=" + Math.random())
        else
            showModel(result)
    });

    $(".btnClose").click(function() {
        $("#alertModal").modal('hide');
    });

    $("#btnSnCheck").click(function() {
        snCheck()
    });

    setTimeout(async function(){
        result = await window.pywebview.api.snCheck()
        if ( result == false){
            $("#labelDate").html("[未激活]")
        } else {
            $("#labelDate").html("["+ result +"]")
        }
    }, 1000)
});


function showModel(message){
    $(".modal-body").html(message)
    $("#alertModal").modal('show');
}


function saveConfig(){
    // 内容保存
    var inputContent = [];
    $('.input-content').each(function() {
        // 当有其中一个为空时全部返回空, 返回空时则不保存
        if ($(this).val() == ''){
            return []
        }
        inputContent.push($(this).val());
    });

    // 通讯录模式保存
    var contracts = {};
    contracts['contractsNumber'] = $("#contractsNumber").val()
    contracts['contractsTime'] = $("#contractsTime").val()
    contracts['timeInterval'] = $("#timeInterval").val()

    if ($('#radioContent').is(":checked")) {
        contracts['radioContent'] = 1
        contracts['radioImage'] = 0
    } else if ($('#radioImage').is(":checked")) {
        contracts['radioContent'] = 0
        contracts['radioImage'] = 1
    } else {
        showModel("没有选项被选中")
    }

    // 通讯录模式保存
    var group = {};
    group['groupKeyword'] = $("#groupKeyword").val()
    group['groupNumber'] = $("#groupNumber").val()
    group['groupMemberNumber'] = $("#groupMemberNumber").val()
    group['groupTime'] = $("#groupTime").val()
    group['timeGroupInterval'] = $("#timeGroupInterval").val()

    if ($('#radioGroupContent').is(":checked")) {
        group['radioGroupContent'] = 1
        group['radioGroupImage'] = 0
        group['radioGroupLastMessage'] = 0
    } else if ($('#radioGroupImage').is(":checked")) {
        group['radioGroupContent'] = 0
        group['radioGroupImage'] = 1
        group['radioGroupLastMessage'] = 0
    } else if ($('#radioGroupLastMessage').is(":checked")) {
        group['radioGroupContent'] = 0
        group['radioGroupImage'] = 0
        group['radioGroupLastMessage'] = 1
    } else {
        showModel("没有选项被选中, 未知错误")
    }

    
    // 通讯录模式保存
    var friend = {};
    friend['friendKeyword'] = $("#friendKeyword").val()
    if (friend['friendKeyword'].length <= 0){
        showModel("好友关键字不能为空")
        return false
    }
    friend['friendNumber'] = $("#friendNumber").val()
    friend['friendTime'] = $("#friendTime").val()
    friend['timeFriendInterval'] = $("#timeFriendInterval").val()
    
    if ($('#radioFriendContent').is(":checked")) {
        friend['radioFriendContent'] = 1
        friend['radioFriendImage'] = 0
        friend['radioFriendLastMessage'] = 0
    } else if ($('#radioFriendImage').is(":checked")) {
        friend['radioFriendContent'] = 0
        friend['radioFriendImage'] = 1
        friend['radioFriendLastMessage'] = 0
    } else if ($('#radioFriendLastMessage').is(":checked")) {
        friend['radioFriendContent'] = 0
        friend['radioFriendImage'] = 0
        friend['radioFriendLastMessage'] = 1
    } else {
        showModel("没有选项被选中, 未知错误")
    }

    // 朋友圈保存
    var moment = {};
    if ($('#checkboxMoment').prop('checked')) {
        moment['checkboxMoment'] = 1
    } else {
        moment['checkboxMoment'] = 0
    }
    moment['momentNumber'] = $("#momentNumber").val()
    moment['timeMomentInterval'] = $("#timeMomentInterval").val()
    
    if ($('#radioMomentContent').is(":checked")) {
        moment['radioMomentContent'] = 1
        moment['radioMomentImage'] = 0
        moment['radioMomentLastMessage'] = 0
    } else if ($('#radioMomentImage').is(":checked")) {
        moment['radioMomentContent'] = 0
        moment['radioMomentImage'] = 1
        moment['radioMomentLastMessage'] = 0
    } else if ($('#radioMomentLastMessage').is(":checked")) {
        moment['radioMomentContent'] = 0
        moment['radioMomentImage'] = 0
        moment['radioMomentLastMessage'] = 1
    } else {
        showModel("没有选项被选中, 未知错误")
    }

    var data = {}
    data.content = inputContent
    data.contracts = contracts
    data.group = group
    data.friend = friend
    data.moment = moment
    window.pywebview.api.saveConfig(data)
}

function qrcode(mac){
    if (!mac) alert("未知错误, 无法得到标识")
    baseUrl = "http://asorder.pro.aisisoft.com.cn/api/Index/nativePay";

    src1Url = baseUrl + "?mac=" + mac + "&type=1"
    $.get(src1Url, function(response) {
        $("#qrcode1").attr("src", response['data']['img1']);
        $("#message1").html(response['data']['message'])
    }).fail(function(xhr, status, error) {
        alert(error);
    });

    src1Ur2 = baseUrl + "?mac=" + mac + "&type=2"
    $.get(src1Ur2, function(response) {
        $("#qrcode2").attr("src", response['data']['img1']);
        $("#message2").html(response['data']['message'])
    }).fail(function(xhr, status, error) {
        alert(error);
    });

    src1Ur3 = baseUrl + "?mac=" + mac + "&type=3"
    $.get(src1Ur3, function(response) {
        $("#qrcode3").attr("src", response['data']['img1']);
        $("#message3").html(response['data']['message'])
    }).fail(function(xhr, status, error) {
        alert(error);
    });
}

function readConfig(data){
    qrcode(data["mac"])
    
    // 设置内容
    $(".content").html("")
    for (var i = 0; i < data["content"].length; i++) {
        htmlStr =   '<div class="input-group mb-3"> \
                        <span class="input-group-text" >评论内容' + (i+1) + '</span> \
                        <textarea class="form-control input-content" style="height:60px">'
                        + data["content"][i] +'</textarea> \
                    </div>'
        
        $(".content").append(htmlStr)
    }

    // 设置通讯录模式
    $("#contractsNumber").val(data['contracts']['contractsNumber'])
    $("#contractsTime").val(data['contracts']['contractsTime'])
    $("#timeInterval").val(data['contracts']['timeInterval'])
    if (data['contracts']['radioContent'] == 1) {
        $('#radioContent').prop('checked', true);
    } else if (data['contracts']['radioImage'] == 1) {
        $('#radioImage').prop('checked', true);
    }

    // 设置群转发模式
    $("#groupKeyword").val(data['group']['groupKeyword'])
    $("#groupMemberNumber").val(data['group']['groupMemberNumber'])
    $("#groupNumber").val(data['group']['groupNumber'])
    $("#groupTime").val(data['group']['groupTime'])
    $("#timeGroupInterval").val(data['group']['timeGroupInterval'])
    if (data['group']['radioGroupContent'] == 1) {
        $('#radioGroupContent').prop('checked', true);
    } else if (data['group']['radioGroupImage'] == 1) {
        $('#radioGroupImage').prop('checked', true);
    } else if (data['group']['radioGroupLastMessage'] == 1) {
        $('#radioGroupLastMessage').prop('checked', true);
    }

    // 设置好友转发模式
    $("#friendKeyword").val(data['friend']['friendKeyword'])
    $("#friendNumber").val(data['friend']['friendNumber'])
    $("#friendTime").val(data['friend']['friendTime'])
    $("#timeFriendInterval").val(data['friend']['timeFriendInterval'])
    if (data['friend']['radioFriendContent'] == 1) {
        $('#radioFriendContent').prop('checked', true);
    } else if (data['friend']['radioFriendImage'] == 1) {
        $('#radioFriendImage').prop('checked', true);
    } else if (data['friend']['radioFriendLastMessage'] == 1) {
        $('#radioFriendLastMessage').prop('checked', true);
    }

    // 设置朋友圈
    if (data['moment']['checkboxMoment'] == 1) {
        $('#checkboxMoment').prop('checked', true);
    }
    $("#momentNumber").val(data['moment']['momentNumber'])
    $("#timeMomentInterval").val(data['moment']['timeMomentInterval'])
    if (data['moment']['radioMomentContent'] == 1) {
        $('#radioMomentContent').prop('checked', true);
    } else if (data['moment']['radioMomentImage'] == 1) {
        $('#radioMomentImage').prop('checked', true);
    } else if (data['moment']['radioMomentLastMessage'] == 1) {
        $('#radioMomentLastMessage').prop('checked', true);
    }
}

// 复制图片
function copyImageToClipboard(imageUrl) {
    var img = new Image();
    img.src = imageUrl;
  
    img.onload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
    
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
    
        canvas.toBlob(function(blob) {
            var item = new ClipboardItem({ 'image/png': blob });
            navigator.clipboard.write([item]).then(function() {

            });
        }, 'image/png');
    };

    img.onerror = function(error) {
    };
}